package com.hibase.core.oss.controller;


import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hibase.common.entity.ResponseModel;
import com.hibase.common.exception.HibaseAssert;
import com.hibase.common.util.EntityUtil;
import com.hibase.core.oss.config.OssProperties;
import com.hibase.core.oss.constant.MimeConstant;
import com.hibase.core.oss.entity.Attachment;
import com.hibase.core.oss.entity.vo.AttachmentHelpVO;
import com.hibase.core.oss.entity.vo.AttachmentListVO;
import com.hibase.core.oss.entity.vo.AttachmentSearchVO;
import com.hibase.core.oss.service.AttachmentService;
import com.hibase.core.oss.util.AliyunOSSUtil;
import com.hibase.core.web.annotation.HibaseGetRequestMapping;
import com.hibase.core.web.annotation.HibasePostRequestMapping;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 附件预览
 * </p>
 *
 * @author hufeng
 * @since 2019-05-20
 */
@Api(tags = "上传附件-new")
@RestController
@RequestMapping("/attachment")
@Slf4j
public class AttachmentPreviewController {

	/**
	 * file downloadSize
	 */
	public static final Integer BUFF_SIZE = 2048;
	
	@Autowired
	private OssProperties ossProperties;

    @Autowired
    private AttachmentService attachmentService;

    /**
     * 上传文件获取uuid
     */
    @ApiOperation(value = "上传获取uuid，提交表单时带上uuid", httpMethod = "POST", response = ResponseModel.class)
    @HibasePostRequestMapping("/uploadFile")
    public ResponseModel uploadFile(@RequestParam("file") MultipartFile multipartFile) {

        String uuid = this.attachmentService.uploadFile(multipartFile);
        return ResponseModel.successMsg(uuid);
    }

    @ApiOperation(value = "下载附件", httpMethod = "GET")
    @HibaseGetRequestMapping("/downloadFile")
    public Object downloadFile(String fileToken, HttpServletResponse response) {

        HibaseAssert.notEmpty(fileToken, "token不能为空");
        // 根据token读取文件路径
        Attachment attachment = getAttachment(fileToken);

        String path = attachment.getFileUrl();
        if (StrUtil.isNotEmpty(path)) {
            try {
                // 暂时通过截取文件后缀
                int index = path.lastIndexOf(".");
                String suffix = path.substring(index + 1);
                if (StrUtil.isNotBlank(suffix)) {
                    response.setContentType(MimeConstant.mimeMap.get(suffix.toLowerCase()));
                }
                String fileName = attachment.getFileName();
                InputStream inputStream = AliyunOSSUtil.downloadFileOssObjStream(ossProperties.getFormalBucket(),path);
                response.setHeader("Content-Length", String.valueOf(attachment.getFileSize()));
                response.setHeader("content-disposition", "attachment;filename="
                        + URLEncoder.encode(attachment.getFileName(), "UTF-8"));
                IoUtil.copy(inputStream, response.getOutputStream());
            }catch (Exception e){
                log.info("文件下载失败 :{}",e.getMessage());
            }
        }
        return null;
    }

    @ApiOperation(value = "附件预览，非图片格式文件转成pdf", httpMethod = "GET")
    @HibaseGetRequestMapping("/viewpage")
    public Object viewpage(String fileToken, HttpServletResponse response) {

        HibaseAssert.notEmpty(fileToken, "fileToken不能为空");
        try {
            // 根据token读取文件路径
            Attachment attachment = getAttachment(fileToken);

            String path = attachment.getFileUrl();

            if (StrUtil.isNotEmpty(path)) {

                // 暂时通过截取文件后缀
                int index = path.lastIndexOf(".");

                String suffix = path.substring(index + 1);
//                String dotSuffix = path.substring(index);
                String fileName = path.substring(path.lastIndexOf(StrUtil.SLASH)+1);
                if(StrUtil.isBlank(fileName)){
                    path = path + attachment.getFileName()+ attachment.getFileType();
                }
//            if (StringUtils.isNotBlank(suffix)) {
//
//                // 如果是指定的文件则转pdf
//                if (Arrays.asList(AttaConstant.CONVERT_PDF_TYPE.split(",")).contains(suffix)) {
//
//                    // pdf的文件命名为当前文件后加_convertpdf
//                    String pdfPath = path.replace(dotSuffix, "") + AttaConstant.CONVERT_PDF_NAME + ".pdf";
//                    // 判断是否有缓存文件
//                    if (!new File(pdfPath).exists()) {
//
//                        // 不存在，则调用openoffice转pdf
//                        ConvertFileUtils.convertPDF(path, pdfPath);
//                    }
//
//                    path = pdfPath;
//                    suffix = "pdf";
//                }
//            }

//            String fileName = path;
//            int fileNameIndex = fileName.lastIndexOf("/");
//
//            if (fileNameIndex > 0) {
//
//                fileName = fileName.substring(fileNameIndex + 1);
//            }

                if (StrUtil.isNotBlank(suffix)) {

                    response.setContentType(MimeConstant.mimeMap.get(suffix.toLowerCase()));
                }

//                InputStream inputStream = AliyunOSSUtil.downloadFileOssObjStream(ossProperties.getFormalBucket(),path);
//                response.setHeader("Content-Length", String.valueOf(attachment.getFileSize()));
//                response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(attachment.getFileName(), "UTF-8"));
//                IoUtil.copy(inputStream, response.getOutputStream());
                
                try(InputStream inputStream = AliyunOSSUtil.downloadFileOssObjStream(ossProperties.getFormalBucket(),path);
                		OutputStream fos = response.getOutputStream()) {
                	
                	Integer length = attachment.getFileSize().intValue();
                	response.setHeader("Content-Length", length.toString());
                	response.setContentType("text/html; charset=UTF-8");
                	response.setContentType("image/jpeg");

        			byte[] buff = new byte[BUFF_SIZE];
        			int flag = -1;
        			while ((flag = inputStream.read(buff)) != -1) {
        				fos.write(buff, 0, flag);
        			}
        			return true;
        		} catch (FileNotFoundException e) {
        			log.error("AttachmentPreviewController viewpage() have a FileNotFoundException,FileNotFoundException={}", e);
        			return false;
        		} catch (IOException e) {
        			log.error("AttachmentPreviewController viewpage() have a IOException,IOException={}", e);
        			return false;
        		}
            }
        }catch (Exception e){
            log.error("文件预览失败 :{}",e.getMessage());
        }
        return null;
    }
    
    private Attachment getAttachment(String token) {
        QueryWrapper<Attachment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("file_token", token);

        Attachment attachment = attachmentService.getOne(queryWrapper, false);

        HibaseAssert.notNull(attachment, "文件不存在");
        return attachment;
    }

    @ApiOperation(value = "获取附件列表", httpMethod = "POST")
    @HibasePostRequestMapping("/selectFileList")
    public ResponseModel<List<AttachmentListVO>> selectFileList(@RequestBody AttachmentSearchVO searchVO) {

        List<Attachment> attachments = this.attachmentService.selectByBiz(EntityUtil.transform(searchVO, Attachment.class));

        return ResponseModel.successMsg(EntityUtil.transform(attachments, AttachmentListVO.class));
    }
    
    
    /**
	 * @Title: WmsPoController
	 * @Description: Excel模板下载
	 * @author TimBrian
	 * @since Jun 18, 2021 3:40:06 PM
	 * @param response
	 * @param fileName
	 */
	@ApiOperation(value = "下载PO模板")
    @HibaseGetRequestMapping(value = "linkPoTemplate")
	public Object linkTemplate(HttpServletResponse response, String fileName){
        try {
        	return attachmentService.linkTemplate(response, fileName);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return ResponseModel.failMsg();
        }
    }
	
	/**
	 * 
	 * @Title: AttachmentPreviewController
	 * @Description: 根据fileTokens获取图片列表
	 * @author TimBrian
	 * @since Jul 29, 2021 5:17:34 PM
	 * @param searchVO
	 * @return
	 */
	@ApiOperation(value = "获取附件列表", httpMethod = "POST")
    @HibasePostRequestMapping("/selectFileListByTokens")
    public ResponseModel<List<AttachmentListVO>> selectFileListByTokens(@RequestBody AttachmentSearchVO searchVO) {

        List<Attachment> attachments = this.attachmentService.selectFileListByTokens(EntityUtil.transform(searchVO, Attachment.class));

        return ResponseModel.successMsg(EntityUtil.transform(attachments, AttachmentListVO.class));
    }
	
	/**
	 * @Title: AttachmentPreviewController
	 * @Description: 保存fileToken入库
	 * @author TimBrian
	 * @since 2021年9月7日 下午5:06:27
	 * @return
	 */
	@ApiOperation(value = "保存fileToken入库", httpMethod = "POST")
	@HibasePostRequestMapping("/saveAttachment")
	public ResponseModel<List<AttachmentListVO>> saveAttachment(@RequestBody AttachmentHelpVO attachmentHelpVO) {
		List<Attachment> attachments = this.attachmentService.saveAttachment(attachmentHelpVO);
		return ResponseModel.successMsg(EntityUtil.transform(attachments, AttachmentListVO.class));
	}
}
